package cloud.xiangyixiang.www.spring.boot.java.basics.controller;

import cloud.xiangyixiang.www.spring.boot.java.basics.pojo.bo.UserTransientBO;

import java.io.*;

/**
 * <p>
 * JAVA Serialization 序列化
 * </p>
 *
 * 【序列化、反序列化】
 * @author zhixinglu
 * @date 2023/9/2 18:31
 */
public class SerializationController {

    /**
     * 数据文件
     */
    private static final String DATA_PATH = System.getProperty("user.dir") + "/spring-boot-java-basics/src/main/resources/data.txt";


    public static void main(String[] args) {
        try {
            SerializeUser();
            DeSerializeUser();
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 序列化
     * @throws IOException
     */
    private static void SerializeUser() throws IOException, NotSerializableException {
        UserTransientBO user = new UserTransientBO();
        user.setUsername("测试人");
        user.setPassword("123456");
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(DATA_PATH));
        oos.writeObject(user);
        oos.close();
        System.out.println("普通字段序列化：username: " + user.getUsername());
        System.out.println("添加了transient关键字序列化：password: " + user.getPassword());
    }

    /**
     * 反序列化
     *  密码不想泄露，添加transient关键字，屏蔽序列化功能
     * @throws IOException
     * @throws ClassNotFoundException
     */
    private static void DeSerializeUser() throws IOException, ClassNotFoundException {
        File file = new File(DATA_PATH);
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file));
        UserTransientBO user = (UserTransientBO)ois.readObject();
        System.out.println("普通字段反序列化：username：" + user.getUsername());
        System.out.println("添加了transient关键字反序列化：password：" + user.getPassword());
    }

}
